<template>
  <PlusDialogForm
    ref="formRef"
    v-model:visible="visible"
    v-model="form"
    :form="{
      columns,
      labelWidth: 100,
      labelPosition: 'right'
    }"
    :dialog="{ title: '密码变更', confirmLoading: loading }"
    @confirm="submit"
  >
    <template #plus-field-password>
      <el-input
        v-model="form.password"
        placeholder="请输入密码"
        type="password"
        show-password
        minlength="6"
      />
    </template>
    <template #plus-field-checkPass>
      <el-input
        v-model="form.checkpass"
        placeholder="请再次输入密码"
        type="password"
        show-password
        minlength="6"
      />
    </template>
  </PlusDialogForm>
</template>

<script setup lang="ts">
import { ref, nextTick } from "vue";
import {
  type PlusColumn,
  PlusDialogForm,
  type FieldValues
} from "plus-pro-components";
import { resetPassword } from "@/api/system/user";
const loading = ref(false);
const form = ref({} as any);

const columns: PlusColumn[] = [
  { label: "账号", prop: "userName", valueType: "text" },
  { label: "用户名称", prop: "nickName", valueType: "text" },
  { label: "角色", prop: "roleName", valueType: "text" },
  { label: "组织", prop: "depts", valueType: "text" },
  {
    label: "新密码",
    prop: "password",
    rules: {
      required: true,
      validator: (rule: any, value: any, callback: any) => {
        if (value.length < 6) {
          callback(new Error("密码最少设置6位以上"));
        } else {
          callback();
        }
      }
    }
  },
  {
    label: "新密码",
    prop: "checkpass",
    rules: {
      required: true,
      validator: (rule: any, value: any, callback: any) => {
        if (!value) {
          callback(new Error("请再次输入密码"));
        } else if (value !== form.value.password) {
          callback(new Error("两次密码输入不一致"));
        } else {
          callback();
        }
      }
    }
  }
];

const visible = ref(false);
const formRef = ref(null);
const show = formdata => {
  visible.value = true;
  const { depts } = formdata;
  let arr = [];
  if (depts) {
    arr = depts.map(item => item.deptName);
  }
  nextTick(() => {
    formRef?.value?.formInstance?.clearValidate();
    form.value = {
      ...formdata,
      depts: arr.join(","),
      password: "",
      checkpass: ""
    };
  });
};
defineExpose({ show });

const emit = defineEmits(["confirm"]);
const submit = () => {
  loading.value = true;
  const { userId, password, warehouseId } = form.value;

  const params = { userId, password, warehouseId };
  resetPassword(params)
    .then(res => {
      loading.value = false;
      emit("confirm");
      visible.value = false;
    })
    .catch(() => {
      loading.value = false;
    });
};
</script>
